<?php
/*
Plugin Name: Simple Sitemap
Plugin URI: http://www.presscoders.com/plugins/free-plugins/simple-sitemap/
Description: HTML sitemap to display content as a single linked list of posts and pages, or as groups sorted by taxonomy (via a drop-down box).
Version: 1.28
Author: David Gwyer
Author URI: http://www.presscoders.com
*/

/*  Copyright 2009 David Gwyer (email : d.v.gwyer@presscoders.com)

    This program is free software; you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation; either version 2 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program; if not, write to the Free Software
    Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
*/

/* To Do:
1. Be able to sort ascending/descending in addition to the sort drop down options for each list.
2. Be able to exclude individual posts/pages.
3. Have styling (in Plugins options page textarea?) to control sitemap rendering.
4. Add all in-line styles to external style sheet.
5. Options to display custom post types, with ability to show which custom post types to display or not display, and in what order?
6. Check which pages the simple-sitemap css is loaded. Don't really want it showing on pages that are not sitemap pages. I think it is loaded on all pages currently?
*/

// wpss_ suffix is derived from [W]ord[P]ress [s]imple [s]itemap
add_shortcode('simple-sitemap', 'wpss_gen');
add_filter('query_vars', 'parameter_queryvars' );
//add_action( 'plugins_loaded', 'wpss_generate' );
add_action('wp_print_styles', 'add_my_stylesheet');

register_activation_hook(__FILE__, 'wpss_add_defaults');
register_uninstall_hook(__FILE__, 'wpss_delete_plugin_options');
add_action('admin_init', 'wpss_init' );
add_action('admin_menu', 'wpss_add_options_page');

// ***************************************
// *** START - Create Admin Options    ***
// ***************************************

// delete options table entries ONLY when plugin deactivated AND deleted
function wpss_delete_plugin_options() {
	delete_option('wpss_options');
}

// Define default option settings
function wpss_add_defaults() {
	$tmp = get_option('wpss_options');
    if(($tmp['chk_default_options_db']=='1')||(!is_array($tmp))) {
		delete_option('wpss_options'); // so we don't have to reset all the 'off' checkboxes too! (don't think this is needed but leave for now)
		$arr = array("drp_pages_default" => "post_title", "drp_posts_default" => "title", "chk_default_options_db" => "0", "rdo_display_order" => "pages_left");
		update_option('wpss_options', $arr);
	}
}

// Init plugin options to white list our options
function wpss_init(){
	// this is primarily to check newly added options have correct initial values
	$tmp = get_option('wpss_options');
	if(!$tmp['rdo_display_order']) // check radio buttons have a starting value
	{
		$tmp["rdo_display_order"] = "pages_left";
		update_option('wpss_options', $tmp);
	}
	register_setting( 'wpss_plugin_options', 'wpss_options', 'wpss_validate_options' );
}

// Add menu page
function wpss_add_options_page() {
	add_options_page('Simple Sitemap Options Page', 'Simple Sitemap', 'manage_options', __FILE__, 'wpss_render_form');
}

// Draw the menu page itself
function wpss_render_form() {
	?>
	<div class="wrap">
		<div class="icon32" id="icon-options-general"><br></div>
		<h2>Simple Sitemap Options</h2>
		<div style="background:#eee;border: 1px dashed #ccc;font-size: 13px;margin-top: 20px;padding: 5px 0 5px 8px;">To display the Simple Sitemap on a post/page, enter the following <a href="http://codex.wordpress.org/Shortcode_API" target="_blank">shortcode</a>: <b>[simple-sitemap]</b></div>
		<div style="margin-top:20px;width:800px;">
			<div style="float:left;width:80%;">Configure the plugin options below. If you like this Plugin, or use it on a commercial website, then <b><em>please</em></b> consider making a <a href="https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=UUFZZU35RZPW8" target="_blank">donation</a> to support continued development of this Plugin.</div>
			<div style="float:right;width:20%;">
				<form action="https://www.paypal.com/cgi-bin/webscr" method="post">
					<input type="hidden" name="cmd" value="_s-xclick">
					<input type="hidden" name="hosted_button_id" value="UUFZZU35RZPW8">
					<input type="image" src="https://www.paypal.com/en_US/GB/i/btn/btn_donateCC_LG.gif" border="0" name="submit" alt="PayPal - The safer, easier way to pay online.">
					<img alt="" border="0" src="https://www.paypal.com/en_GB/i/scr/pixel.gif" width="1" height="1">
				</form>
			</div>
		</div>
		<form method="post" action="options.php">
			<?php settings_fields('wpss_plugin_options'); ?>
			<?php $options = get_option('wpss_options'); ?>
			<table class="form-table">
				<tr valign="top">
					<th scope="row">Content Display Order</th>
					<td>
						<label><input name="wpss_options[rdo_display_order]" type="radio" value="posts_left" <?php checked('posts_left', $options['rdo_display_order']); ?> /> Display <u>Posts</u> on LHS&nbsp;&nbsp;<small style="color: #999;">(with pages on the RHS)</small></label><br />
						<label><input name="wpss_options[rdo_display_order]" type="radio" value="pages_left" <?php checked('pages_left', $options['rdo_display_order']); ?> /> Display <u>Pages</u> on LHS&nbsp;&nbsp;<small style="color: #999;">(with posts on the RHS)</small></label><br />
					</td>
				</tr>
				<tr>
					<th scope="row">Pages Drop-Down Default</th>
					<td>
						<select style="width:90px;" name='wpss_options[drp_pages_default]'>
							<option value='post_title' <?php selected('post_title', $options['drp_pages_default']); ?>>Title</option>
							<option value='post_date' <?php selected('post_date', $options['drp_pages_default']); ?>>Date</option>
							<option value='post_author' <?php selected('post_author', $options['drp_pages_default']); ?>>Author</option>
						</select>
					</td>
				</tr>
				<tr>
					<th scope="row">Posts Drop-Down Default</th>
					<td>
						<select style="width:90px;" name='wpss_options[drp_posts_default]'>
							<option value='title' <?php selected('title', $options['drp_posts_default']); ?>>Title</option>
							<option value='date' <?php selected('date', $options['drp_posts_default']); ?>>Date</option>
							<option value='author' <?php selected('author', $options['drp_posts_default']); ?>>Author</option>
							<option value='category' <?php selected('category', $options['drp_posts_default']); ?>>Category</option>
							<option value='tags' <?php selected('tags', $options['drp_posts_default']); ?>>Tags</option>
						</select>
					</td>
				</tr>
				<tr><td colspan="2"><div style="margin-top:10px;"></div></td></tr>
				<tr valign="top" style="border-top:#dddddd 1px solid;">
					<th scope="row">Database Options</th>
					<td>
						<label><input name="wpss_options[chk_default_options_db]" type="checkbox" value="1" <?php checked('1', $options['chk_default_options_db']); ?> /> Restore Plugin defaults upon deactivation/reactivation</label>
						<br /><span style="color:#666666;margin-left:2px;">Only check this if you want to reset plugin settings upon reactivation</span>
					</td>
				</tr>
			</table>
			<p class="submit">
			<input type="submit" class="button-primary" value="<?php _e('Save Changes') ?>" />
			</p>
		</form>

<div><strong>*New* Plugin Support Forum!</strong><a id="pc_support_toggle" href="#" title="status" style="margin-left:5px;"><small>(click to expand)</small></a></div>
<div id="pc_support" style="display:none;background:#eeeeee;border:1px solid #bbbbbb;margin-top:10px;padding:15px;">
<h3 style="margin:0px 0px 15px 0px;padding:0px;">Please help support the development of this plugin.</h3>

<div style="margin-bottom:10px;">Would you like this plugin to..</div>
<ul>
<li> - be supported on a FULL time basis?</li>
<li> - always work with the latest version of WordPress?</li>
<li> - have updates regularly released?</li>
<li> - be fixed quickly should any bugs/security issues arise?</li>
<li> - give you peace of mind and ALWAYS work on your website whether it is a business site, or personal?</li>
</ul>
<div style="margin-top:10px;">If you answered YES to any of these questions then you may wish to <a href="http://www.presscoders.com/members/signup.php" target="_blank">sign-up to our exclusive support package</a>, which is available to all users of our FREE plugins.</div>
<div style="margin-top:10px;">We are dedicated to bringing our users a range of high quality, stable FREE plugins. The only way we can continue to do this by providing support to users to cover the full time development of these plugins. We have many more plugins on the drawing board. Please help us to convert these ideas into working active plugins!</div>
<div style="margin-top:10px;">Click <a href="http://www.presscoders.com/wordpress-support/" target="_blank">here</a> for full details of support available for Simple Sitemap.</div>
<div style="margin-top:10px;">Or <a href="http://www.presscoders.com/members/signup.php" target="_blank">sign-up straight away</a> to get immediate access to support!</div>
</div>
<script>
	jQuery("#pc_support_toggle").click(function(){
		jQuery("#pc_support").toggle(400);
	});
</script>

	<p style="margin-top:20px;">Follow me on <a href="http://twitter.com/dgwyer" target="_blank">twitter</a>. Also, check out our new site: <a href="http://www.presscoders.com" target="_blank">PressCoders.com</a></p>

	</div>
	<?php	
}

// Sanitize and validate input. Accepts an array, return a sanitized array.
function wpss_validate_options($input) {
	 // strip html from textboxes
	// e.g. $input['textbox'] =  wp_filter_nohtml_kses($input['textbox']);
	return $input;
}

// ***************************************
// *** END - Create Admin Options    ***
// ***************************************

// ---------------------------------------------------------------------------------

// ***************************************
// *** START - Plugin Core Functions   ***
// ***************************************

function add_my_stylesheet() {
	$styleSheet = WP_PLUGIN_URL.'/simple-sitemap/css/ss_style.css';
	wp_register_style('myStyleSheets', $styleSheet);
	wp_enqueue_style( 'myStyleSheets');
}

function parameter_queryvars( $qvars ) {
	$qvars[] = 'pagesort';
	$qvars[] = 'postsort';
	return $qvars;
}

function page_params() {
	global $wp_query;
	if (isset($wp_query->query_vars['pagesort'])) {
		return $wp_query->query_vars['pagesort'];
	}
}

function post_params() {
	global $wp_query;
	if (isset($wp_query->query_vars['postsort'])) {
		return $wp_query->query_vars['postsort'];
	}
}

// shortcode function
function wpss_gen() {
	ob_start(); // start output caching (so that existing content in the [simple-sitemap] post doesn't get shoved to the bottom of the post

	global $post; //wordpress post global object
	$permalink_structure = get_option( 'permalink_structure' );
	if($permalink_structure == null) {
		$link_url = get_permalink($post->ID);
		$query_symbol = '&';	// add a '&' character prefix onto the query string
	}
	else if((substr($permalink_structure, -1)) != '/') {
		$link_url = get_permalink($post->ID).'/';
		$query_symbol = '?';	// add a '?' character prefix onto the query string
	}
	else {
		$link_url = get_permalink($post->ID);
		$query_symbol = '?';	// add a '?' character prefix onto the query string
	}

    // sort by value in drop down box (make sure drop down default is title which is the default used by wp_list_pages)
    $page_params = page_params();
    $post_params = post_params();

	$opt = get_option('wpss_options');
	//echo '$opt[\'drp_pages_default\'] = '.$opt['drp_pages_default'].'<br />';
	//echo '$opt[\'drp_posts_default\'] = '.$opt['drp_posts_default'].'<br />';

	if($page_params == null ) {
		if($opt['drp_pages_default'] == "post_title") {	$page_params = 'menu_order, post_title'; }
		else if ($opt['drp_pages_default'] == "post_date") { $page_params = 'post_date'; }
		else { $page_params = 'post_author'; }
	}
	$page_args=array( 'sort_column' => $page_params, 'title_li' => '');

	if($post_params == null ) {
		if($opt['drp_posts_default'] == "title") { $post_params = 'title'; }
		else if ($opt['drp_posts_default'] == "date") { $post_params = 'date'; }
		else if ($opt['drp_posts_default'] == "author") { $post_params = 'author'; }
		else if ($opt['drp_posts_default'] == "category") { $post_params = 'category'; }
		else { $post_params = 'tags'; }
	}
	$post_args=array( 'orderby' => $post_params, 'posts_per_page' => -1, 'order' => 'asc' );

	//echo "<br />Page Args: <br />";
	//print_r($page_args);
	//echo "<br /><br />Posts Args: <br />";
	//print_r($post_args);
	//echo "<br /><br />Page Params: $page_params";
	//echo "<br />Post Params: $post_params";

	// Initialise to "" to prevent undefined variable error
	$pt1=$pd1=$pa1=$pt2=$pd2=$pa2=$pc2=$ptg2="";

	// page drop down box	
	if($page_params == 'menu_order, post_title') {
		$pt1 = "selected='selected'";
	}
	else if($page_params == 'post_date') {
		$pd1 = "selected='selected'";
	}
	else if($page_params == 'post_author') {
		$pa1 = "selected='selected'";
	}

	// post drop down box	
	if($post_params == 'title') {
		$pt2 = "selected='selected'";
	}
	else if($post_params == 'date') {
		$pd2 = "selected='selected'";
	}
	else if($post_params == 'author') {
		$pa2 = "selected='selected'";
	}
	else if($post_params == 'category') {
		$pc2 = "selected='selected'";
	}
	else if($post_params == 'tags') {
		$ptg2 = "selected='selected'";
	}
?>
<div class="ss_wrapper">
		<?php
			$opt = get_option('wpss_options');
			if($opt['rdo_display_order'] == "pages_left") {
				$pages_float = "float:left;";
			}
			else {
				$pages_float = "float:right;";
			}
		?>
		<div id="ss_pages" style="<?php echo $pages_float ?>">
			<h2 class='page_heading'>Pages</h2>
			
			<div id="page_drop_down">
				<span id="page_dd_label">Show pages by:</span>
				<select>
					<option onClick="location.href='<?php echo $link_url.$query_symbol.'pagesort=post_title'; ?>'" <?php echo $pt1; ?>>Title</option>
					<option onClick="location.href='<?php echo $link_url.$query_symbol.'pagesort=post_date'; ?>'" <?php echo $pd1; ?>>Date</option>
					<option onClick="location.href='<?php echo $link_url.$query_symbol.'pagesort=post_author'; ?>'" <?php echo $pa1; ?>>Author</option>
				</select>
			</div>
			<?php
			if(strpos($page_params, 'post_date') !== false) {
				echo '<ul class="page_item_list">';
				$page_args=array('sort_order' => 'desc', 'sort_column' => 'post_date', 'date_format' => ' (m.d.y)', 'show_date'=> 'created', 'title_li' => '');
				wp_list_pages($page_args); // show the sorted pages
				echo '</ul>';
			}
			elseif(strpos($page_params, 'post_author') !== false) {
				$authors = get_users_of_blog(); //gets registered users
				foreach ($authors as $author) {
					$empty_page_args=array('echo' => 0, 'authors' => $author->user_id, 'title_li' => '');
					$empty_test = wp_list_pages($empty_page_args); // test for authors with zero pages
					//echo '$empty_test = '.$empty_test;
					
					if($empty_test != null || $empty_test != "") {
						echo "<div class='page_author'>$author->display_name</div>";
						echo "<div class=\"ss_date_header\"><ul class=\"page_item_list\">";
						$page_args=array('authors' => $author->user_id, 'title_li' => '');
						wp_list_pages($page_args);
						echo "</ul></div>";
					}
					else {
						echo "<div class='page_author'>$author->display_name <span class=\"ss_sticky\">(no pages published)</span></div>";
					}
				} ?>
			<?php
			}
			else { // default = title
				echo '<ul class="page_item_list">';
				wp_list_pages($page_args); // show the sorted pages
				echo '</ul>';
			}
			?>
		</div><!--ss_pages -->
		<div id="ss_content_sep"></div>
		<?php
			$opt = get_option('wpss_options');
			if($opt['rdo_display_order'] == "pages_left") {
				$posts_float = "float:right;";
			}
			else {
				$posts_float = "float:left;";
			}
		?>
		<div id="ss_posts" style="<?php echo $posts_float ?>">
			<h2 class='post_heading'>Posts</h2>
			<div id="post_drop_down">
				<span id="post_dd_label">Show posts by:</span>
				<select>
					<option onClick="location.href='<?php echo $link_url.$query_symbol.'postsort=title'; ?>'" <?php echo $pt2; ?>>Title</option>
					<option onClick="location.href='<?php echo $link_url.$query_symbol.'postsort=date'; ?>'" <?php echo $pd2; ?>>Date</option>
					<option onClick="location.href='<?php echo $link_url.$query_symbol.'postsort=author'; ?>'" <?php echo $pa2; ?>>Author</option>
					<option onClick="location.href='<?php echo $link_url.$query_symbol.'postsort=category'; ?>'" <?php echo $pc2; ?>>Category</option>
					<option onClick="location.href='<?php echo $link_url.$query_symbol.'postsort=tags'; ?>'" <?php echo $ptg2; ?>>Tags</option>
				</select>
			</div>
			<?php
			if(strpos($post_params, 'category') !== false) {
				$categories = get_categories();
				foreach ($categories as $category) {
					$category_link = get_category_link($category->term_id);
					$cat_count = $category->category_count;

					echo '<div class="ss_cat_header"><a href="'.$category_link.'">'.ucwords($category->cat_name).'</a> ';
					query_posts('post_status=publish&cat='.$category->term_id); // show the sorted posts ?>
					<?php
						global $wp_query;	
						echo '('.$wp_query->post_count.')</div>'; ?>
					<?php
					if (have_posts()) :
						echo '<div class="post_item_list"><ul class="post_item_list">';
						while (have_posts()) :
							the_post(); ?>
							<li class="post_item">
								<a href="<?php the_permalink() ?>" rel="bookmark" title="Permanent Link to <?php the_title_attribute(); ?>"><?php the_title(); ?></a>
							</li>
						<?php  endwhile;
						echo '</ul></div>';
					endif;
					wp_reset_query();
				}
			}
			else if(strpos($post_params, 'author') !== false) {
				$authors = get_users_of_blog(); //gets registered users
				foreach ($authors as $author) {
					echo '<a href="'.get_author_posts_url($author->user_id).'">'.$author->display_name.'</a> ';
					query_posts('post_status=publish&author='.$author->user_id); // show the sorted posts ?>
					<?php
					global $wp_query;	
					echo '('.$wp_query->post_count.')'; ?>
					<?php
					if (have_posts()) :
						echo '<div class="post_item_list"><ul class="post_item_list">';
						while (have_posts()) :
							the_post(); ?>
							<li class="post_item">
								<a href="<?php the_permalink() ?>" rel="bookmark" title="Permanent Link to <?php the_title_attribute(); ?>"><?php the_title(); ?></a>
							</li>
						<?php  endwhile;
						echo '</ul></div>';
					endif;
					wp_reset_query();
				}
			}
			else if(strpos($post_params, 'tags') !== false) {
				$post_tags = get_tags();
				echo '<div class="ss_tag_header">';
				foreach ($post_tags as $tag){
					$tag_link = get_tag_link($tag->term_id);
					echo "<a href='{$tag_link}' title='{$tag->name} Tag' class='{$tag->slug}'>";
					echo "{$tag->name}</a> ($tag->count)";

					query_posts('post_status=publish&tag='.$tag->slug); // show posts ?>
					<?php
					if (have_posts()) :
						echo '<div class="post_item_list"><ul class="post_item_list">';
						while (have_posts()) :
							the_post(); ?>
							<li class="post_item">
								<a href="<?php the_permalink() ?>" rel="bookmark" title="Permanent Link to <?php the_title_attribute(); ?>"><?php the_title(); ?></a>
							</li>
						<?php  endwhile;
						echo '</ul></div>';
					endif;
					wp_reset_query();
				}
				echo '</div>';
			}
			else if(strpos($post_params, 'date') !== false) {
				?><div class="ss_date_header">
				<?php
				global $wpdb;
				$months = $wpdb->get_results("SELECT DISTINCT MONTH(post_date) AS month , YEAR(post_date) AS year FROM $wpdb->posts WHERE post_status = 'publish' and post_date <= now( ) and post_type = 'post' GROUP BY month, year ORDER BY post_date DESC");
				foreach($months as $curr_month){
					query_posts('post_status=publish&monthnum='.$curr_month->month.'&year='.$curr_month->year); // show posts ?>
					<?php
					global $wp_query;	
					echo "<a href=\"";
					echo get_month_link($curr_month->year, $curr_month->month);
					echo '">'.date( 'F', mktime(0, 0, 0, $curr_month->month) ).' '.$curr_month->year.'</a> ('.$wp_query->post_count.')'; ?>
					<?php
					if (have_posts()) :
						echo '<div class="post_item_list"><ul class="post_item_list">';
						while (have_posts()) :
							the_post(); ?>
							<li class="post_item">
								<a href="<?php the_permalink() ?>" rel="bookmark" title="Permanent Link to <?php the_title_attribute(); ?>"><?php the_title(); ?></a>
							</li>
						<?php  endwhile;
						echo '</ul></div>';
					endif;
					wp_reset_query();
				} ?>
				</div>
			<?php
			}
			else { // default = title
			?>
				<?php query_posts($post_args); // show the sorted posts
					if (have_posts()) :
						echo '<ul class="post_item_list">';
						while (have_posts()) :
							the_post();
							$sticky="";
							if(is_sticky(get_the_ID())) { $sticky=" (sticky post)"; } ?>
							<li class="post_item">
								<a href="<?php the_permalink() ?>" rel="bookmark" title="Permanent Link to <?php the_title_attribute(); ?>"><?php the_title(); ?></a>
								<?php if ( $sticky == ' (sticky post)' ) : ?>
									<span class="ss_sticky"><?php echo $sticky; ?></span>
								<?php endif; ?>
							</li>
						<?php  endwhile;
						echo '</ul>';
					endif;
					wp_reset_query();
			}
			?>
		</div><!--ss_posts-->
</div>
<?php

$output = ob_get_contents();;
ob_end_clean();

return $output;

}
// ***************************************
// *** END - Plugin Core Functions     ***
// ***************************************
?>